package com.hzy.orderSystem.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzy.orderSystem.dao.RecordDao;
import com.hzy.orderSystem.entities.Order;
import com.hzy.orderSystem.entities.Record;
import com.hzy.orderSystem.entities.User;
import com.hzy.orderSystem.service.OrderService;
import com.hzy.orderSystem.service.RecordService;
import com.hzy.orderSystem.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 小宝
 * @create 2021/4/17 10:35
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    OrderService orderService;
    @Autowired
    RecordService recordService;

    /**
     * 提出问题，添加工单并添加问题
     * @param map  question: 问题
     * @param request
     * @return
     */
    @PostMapping("/add")
    public CommonResult addOrder(@RequestBody Map<String, String> map,
                                 HttpServletRequest request){
        String question = map.get("content");
        String token = request.getHeader("X-Token");

        User user = (User)redisTemplate.opsForValue().get(token);
        if(user != null){
            Order order = new Order(0, user);
            int save = orderService.save(order);
            if(save > 0){
                // 获取当前时间
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Record record = new Record(question, sdf.format(date), 0, order);
                save = recordService.save(record);
                if(save > 0){
                    JSONObject data = new JSONObject();
                    data.put("content", record.getContent());
                    data.put("type", record.getType());
                    data.put("time", record.getTime());
                    data.put("username", order.getUser().getUsername());
                    return new CommonResult(20000, "客服马上来，请稍等", data);
                }
            }
             // 这里还需处理添加，但未添加问题的删除逻辑
            return new CommonResult(40000, "提问失败，请重新提问");
        }else
            return new CommonResult(40000, "账号已失效，请重新登录");
    }

    /**
     * 获取当前工单下的所有历史记录
     * @param id 工单id
     * @return
     */
    @GetMapping("/records/{id}")
    public CommonResult getRecords(@PathVariable Long id){
        Order order = orderService.getRecords(id);
        JSONArray data = new JSONArray();
        for(Record record : order.getRecords()){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("content", record.getContent());
            jsonObject.put("time", record.getTime());
            jsonObject.put("type", record.getType());
            if(record.getType() == 1)
                jsonObject.put("username", record.getSupport().getUsername());
            else
                jsonObject.put("username", order.getUser().getUsername());
            data.add(jsonObject);
        }
        return new CommonResult(20000, "获取记录列表成功", data);
    }

    /**
     * 获取工单列表
     * @param map
     *      uid: 查找用户所有工单
     *      uid + status[0,1]: 查找用户的有效工单
     *      sid + status[0,1]: 查找客服跟进工单
     *      status[0]: 待办工单，查找有效的需要处理的工单
     * @return
     */
    @PostMapping("/orders")
    public CommonResult getOrders(@RequestBody Map<String, Object> map){
        Long uid = null;
        Long sid = null;
        List<Integer> status = null;
        if(map.get("uid") != null)
            uid = Long.parseLong(map.get("uid").toString());
        if(map.get("sid") != null){
            sid = Long.parseLong(map.get("sid").toString());

        }
        if(map.get("status") != null)
            status = (List<Integer>) map.get("status");
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        int pageNum = Integer.parseInt(map.get("pageNum").toString());

        PageHelper.startPage(pageNum, pageSize);
        // 查跟进工单
        // 查之前先验证跟进工单的状态是否在有效期
        Page<Order> orders = orderService.getOrders(uid, sid, status);

        JSONObject data = new JSONObject();
        data.put("total", orders.getTotal());
        JSONArray array = new JSONArray();
        for(Order order : orders){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", order.getId());
            jsonObject.put("status", order.getStatus());
            for(Record record : order.getRecords()){
                if(record.getType() == 0){
                    jsonObject.put("questionTime", record.getTime());
                    jsonObject.put("question", record.getContent());
                }
                else{
                    jsonObject.put("answerTime", record.getTime());
                    jsonObject.put("answer", record.getContent());
                }
            }
            array.add(jsonObject);
        }
        data.put("orders", array);
        return new CommonResult(20000, "获取工单列表成功", data);
    }

    @PutMapping("/update")
    public CommonResult updateOrder(@RequestBody Order order){
        int update = orderService.updateOrder(order);
        if(update > 0)
            return new CommonResult(20000, "已终结该工单");
        else
            return new CommonResult(40000, "终结工单失败");
    }

}
